<?php

namespace App\Http\Controllers;

use App\Repository\Service\ServiceCallRepository;
use App\Repository\UploadRepository;
use Illuminate\Http\Request;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;


class UploadController extends Controller
{
    public $upload = './attach';
    public $log;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->log = new Logger('Upload');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/Upload.log'), 5, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
    }

    // 图片上传方法
    public function upload(Request $Request)
    {
        if (empty($Request->user)) {
            return [
                'code' => 1,
                'msg' => '上传验证账号失败',
                'fileName' => ''
            ];
        }
        $model = new UploadRepository();
        $res = $model->upload($Request, 'file');
        if (empty($res['file_src'])) {
            return [
                'code' => 100,
                'msg' => '上传失败',
                'fileName' => ''
            ];
        }
        return [
            'code' => 200,
            'fileName' => $res['file_src']
        ];
    }

    public function uploadPdf(Request $Request)
    {
        if (empty($Request->user)) {
            return [
                'code' => 1,
                'msg' => '上传验证账号失败',
                'fileName' => ''
            ];
        }
        $model = new UploadRepository();
        $res = $model->upload($Request, 'file', false, 1, 'pdf');
        if (empty($res['file_src'])) {
            return [
                'code' => 100,
                'msg' => '上传失败',
                'fileName' => ''
            ];
        }
        return [
            'code' => 200,
            'fileName' => $res['file_src']
        ];
    }

    public function uploadMp3(Request $Request)
    {
        if (empty($Request->user)) {
            return [
                'code' => 1,
                'msg' => '上传验证账号失败',
                'fileName' => ''
            ];
        }
        $params = $Request->all();
        unset($params['Authorization']);
//        $this->log->info("上传内容:" . json_encode($params));
//        上传文件接收并保存
        $model = new UploadRepository();
        $file_src = '';
        if ($Request->has('recordFile')) {
            //        上传文件接收并保存
            $res = $model->upload($Request, 'recordFile', false, 1, 'record');
            $file_src = $res['recordFile_src'] ?? '';
            $this->log->info("录音上传结果:" . json_encode($res));
        }
//        上传的文件保存
        $params['record'] = $file_src;
        $Repository = new ServiceCallRepository();
        $data = $Repository->savePushCallResult($params);
        return $data['code'] === 200 ? 'true' : 'false';
    }
}
